// 107. 二叉树的层序遍历 II

#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

struct TreeNode 
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root)
    {
        vector<vector<int>> ret;
        if(!root) return ret;

        // 用队列存每一层的节点
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()) // 队列不为空就说明层序没有遍历完
        {
            int n = q.size();
            vector<int> v;
            for(int i = 0; i < n; i++)
            {
                TreeNode* front = q.front(); // 不断出队头
                q.pop();
                v.push_back(front->val);

                if(front->left) q.push(front->left);
                if(front->right) q.push(front->right);
            }
            ret.push_back(v); // 层序的数组入二维数组
        }
        reverse(ret.begin(), ret.end()); // 逆置数组

        return ret;
    }
};